package com.wolfeyes.framework.springsecurity.utils;

import com.wolfeyes.common.constant.HttpStatusConstants;
import com.wolfeyes.framework.springsecurity.domain.model.CustomizeUserDetails;
import com.wolfeyes.common.exception.CustomException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @description SpringSecurity安全认证权限框架工具类
 * @title 获取登录用户身份权限对象信息的工具类
 * @author yanyljava
 * @create 2020-09-04 10:44
 */
public class SecurityUtils {

	/**
	 * @title 获取用户账户
	 */
	public static String getUsername() {
		
		try
		{
			return getCustomizeUserDetails().getUsername();
		}
		catch (Exception e)
		{
			throw new CustomException(HttpStatusConstants.UNAUTHORIZED, "获取用户账户异常");
		}
	}

	/**
	 * @title 获取用户
	 */
	public static CustomizeUserDetails getCustomizeUserDetails() {
		
		try
		{
			return (CustomizeUserDetails) getAuthentication().getPrincipal();
		}
		catch (Exception e)
		{
			throw new CustomException(HttpStatusConstants.UNAUTHORIZED, "获取用户信息异常");
		}
	}

	/**
	 * @title 获取Authentication
	 */
	public static Authentication getAuthentication() {
		
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * @title 生成BCryptPasswordEncoder密码
	 * @param password 密码
	 * @return 加密字符串
	 */
	public static String encryptPassword(String password) {
		
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.encode(password);
	}

	/**
	 * @title 判断密码是否相同
	 * @param rawPassword 真实密码
	 * @param encodedPassword 加密后字符
	 * @return 结果
	 */
	public static boolean matchesPassword(String rawPassword, String encodedPassword) {
		
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.matches(rawPassword, encodedPassword);
	}

	/**
	 * @title 是否为管理员
	 * @param userId 用户ID
	 * @return 结果
	 */
	public static boolean isAdmin(Long userId) {
		
		return userId != null && 1L == userId;
	}

}


